const svgCaptcha = require('svg-captcha')
const Utils = require('../../utils');
const User = require('../../models/admin_users');
const Menu = require('../../models/admin_menu');
const Role = require('../../models/admin_role');
const UserOrRole = require('../../models/admin_user_or_role');
const RoleOrMenu = require('../../models/admin_menu_or_role');
const authCodeFunc = require('../../utils/authCode');

/**
 * 登录控制器
 */
const ControllerLogin = {
    // 图文验证码
    sendCaptcha: async function (req, res, next) {
        try {
            var rgba = Utils.randomColor(255, 255)

            const captcha = svgCaptcha.create({
                size: 4,
                ignoreChars: '0o1i',
                // noise: 4,
                background: rgba,
                width: 130,
                height: 40,
            });

            req.session.captcha = captcha.text;

            res.json({
                code: 200,
                svgData: String(captcha.data)
            })

        } catch (e) {
            res.json({
                code: 0,
                data: e
            })
        }
    },

    // 用户登录
    userLogin: async function (req, res, next) {
        try {
            let sessionCaptcha = req.session.captcha ? req.session.captcha.toLowerCase() : '';
            let user_account = req.body.user_account;
            let password = req.body.user_password;
            let captcha = req.body.captcha.toLowerCase();

            const users = await User.select({
                user_account
            });
            const user = users[0];

            if (user) {
                let PSWDECODE = authCodeFunc(user.user_password, 'DECODE'); // 密码解密

                if (password != PSWDECODE.str) return res.json({
                    code: 0,
                    msg: '密码错误！'
                });

                if (!sessionCaptcha) return res.json({
                    code: 0,
                    msg: '验证码已过期！'
                });

                if (captcha != sessionCaptcha) return res.json({
                    code: 0,
                    msg: '验证码错误！'
                });

                if (user.status === 1) return res.json({
                    code: 0,
                    msg: '账号已被冻结，请联系博主'
                });

                let id = user.id;
                let name = user.user_name;
                let avatar = user.user_avatar_url;
                let PSWENCODE = authCodeFunc(password, 'ENCODE');

                let auth_Code = id + '\t' + PSWENCODE;

                const token = authCodeFunc(auth_Code, 'ENCODE');

                await User.update(id, {
                    user_password: PSWENCODE
                });

                res.json({
                    code: 200,
                    msg: '登录成功',
                    data: {
                        token,
                        userInfo: {
                            account: user_account,
                            name,
                            avatar
                        }
                    }
                })

            } else {

                res.json({
                    code: 0,
                    msg: '登录失败，没有此用户！'
                })
            }

        } catch (e) {
            res.json({
                code: 0,
                data: e
            })
        }
    },

    // 退出登录
    userExit: async function (req, res, next) {
        try {
            let authorization = req.headers.authorization;

            if (!authorization) return res.json({
                code: 0,
                msg: '退出失败'
            })

            let token = authorization.split(' ');
            let user_decode = authCodeFunc(token[1], 'DECODE');
            let user_info = user_decode.str.split('\t');
            let id = user_info[0];

            await User.update(id, {
                section_key: 0
            }); // 退出登录

            res.json({
                code: 200,
                msg: '退出成功'
            })
        } catch (e) {
            res.json({
                code: 0,
                data: e
            })
        }
    },

    // 获取权限菜单
    getAuthMenuList: async function (req, res, next) {
        try {
            let authorization = req.headers.authorization;
            let user_id = null;
            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                let user_info = user_decode.str.split('\t');
                user_id = user_info[0];
            }

            const menus = await Menu.all();
            const user_role = await UserOrRole.select({
                user_id
            })

            let role_id = user_role[0].role_id || 0;

            const role_menu = await RoleOrMenu.select({
                role_id
            });

            let menu_ids = role_menu[0].menu_ids.split(',');
            let arr = [];
            let menuList = [];

            menu_ids.forEach((item, index) => {
                arr.push(Object.assign({
                    id: item
                }))
            })

            menus.forEach(data => {
                arr.forEach(e => {
                    if (data.id == e.id) {
                        menuList.push(data)
                    }
                })
            })

            res.json({
                code: 200,
                data: menuList
            })
        } catch (e) {
            res.json({
                code: 0,
                data: e
            })
        }
    },

    // 获取用户详情
    getUserDetail: async function (req, res, next) {
        try {
            let authorization = req.headers.authorization;
            let userInfo = null;

            if (authorization) {
                let token = authorization.split(' ');
                let user_decode = authCodeFunc(token[1], 'DECODE');
                userInfo = user_decode.str.split('\t');
            }

            let id = userInfo[0] || 0;

            const users = await User.select({
                id
            });

            const user_role = await UserOrRole.select({
                user_id: id
            })

            let role_id = user_role[0].role_id;

            const roles = await Role.select({
                id: role_id
            });

            let user = users[0];

            let data = {
                account: user.user_account,
                role_name: roles[0].name,
                avatar: user.user_avatar_url,
                name: user.user_name,
            }


            res.json({
                code: 200,
                data: data
            })
        } catch (e) {
            res.json({
                code: 0,
                data: e
            })
        }
    },
}

module.exports = ControllerLogin;